package org.halk.job_admin.mq.cosumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.halk.job_admin.mapper.ScheduleLogMapper;
import org.halk.job_admin.mapper.ScheduleMapper;
import org.halk.job_admin.pojo.entity.JobResponse;
import org.halk.job_admin.pojo.entity.Schedule;
import org.halk.job_admin.pojo.entity.ScheduleLog;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @Author haozhu7
 * @Date 2024/9/27 23:25
 **/
@Slf4j
@Component
@RocketMQMessageListener(topic = JobResultConsumer.HALK_JOB_RESULT, consumerGroup = JobResultConsumer.HALK_JOB_RESULT, messageModel = MessageModel.CLUSTERING)
public class JobResultConsumer implements RocketMQListener<JobResponse> {

    public static final String HALK_JOB_RESULT = "HALK_JOB_RESULT";

    @Resource
    private ScheduleLogMapper scheduleLogMapper;
    @Resource
    private ScheduleMapper scheduleMapper;

    @Override
    public void onMessage(JobResponse jobResponse) {
        ScheduleLog scheduleLog = this.scheduleLogMapper.queryByMsgId(jobResponse.getMsgId());
        if (scheduleLog == null) {
            log.info("job_result receive msg: {}，为查到对应得记录msgId: {}", jobResponse, jobResponse.getMsgId());
            return;
        }

        Schedule schedule = this.scheduleMapper.queryByScheduleId(jobResponse.getScheduleId());
        if (schedule == null) {
            log.info("job_result receive msg: {}，未查到对应得定时任务 scheduleId: {}", jobResponse, jobResponse.getScheduleId());
            return;
        }

        //判断执行状态
        int status = judgeStatus(jobResponse.getStatus(), schedule.getTimeout(), scheduleLog.getStartTime(), jobResponse.getEndTime());
        scheduleLog.setStatus(status);
        scheduleLog.setDescription(jobResponse.getError());
        scheduleLog.setEndTime(jobResponse.getEndTime());
        this.scheduleLogMapper.updateById(scheduleLog);
        log.info("接收到定时任务回调: {}， {}", jobResponse, scheduleLog);
    }

    /**
     * 判断执行状态
     * @param status  0拒绝执行，1执行成功，2执行失败
     * @param timeout
     * @param startTime
     * @param endTime
     * @return
     */
    private int judgeStatus(Integer status, Integer timeout, LocalDateTime startTime, LocalDateTime endTime) {
        if (status == 0) {
            return 3;
        }

        Duration duration = Duration.between(startTime, endTime);
        long seconds = duration.getSeconds();
        boolean timeoutFlag = seconds - timeout > 0;

        if (status == 1) {
            if (timeoutFlag) {
                return 5;
            } else {
                return 1;
            }
        } else {
            if (timeoutFlag) {
                return 6;
            } else {
                return 2;
            }
        }
    }

}
